clavarium 0.2.340-next.1 → 0.2.342-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,19 +1,19 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.340-next.1",
3
+ "version": "0.2.342-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.340-next.1",
9
+ "version": "0.2.342-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
13
13
  "@xterm/xterm": "^6.0.0",
14
14
  "clavarium-binder": "0.1.61-next.1",
15
15
  "clavarium-docket": "0.1.2-next.2",
16
- "clavarium-parley": "0.17.71-next.1",
16
+ "clavarium-parley": "0.17.74-next.1",
17
17
  "clavarium-tether": "0.1.0-next.54",
18
18
  "mammoth": "1.13.0",
19
19
  "mermaid": "11.17.2",
@@ -787,9 +787,9 @@
787
787
  }
788
788
  },
789
789
  "node_modules/clavarium-parley": {
790
- "version": "0.17.71-next.1",
791
- "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.71-next.1.tgz",
792
- "integrity": "sha512-98RGnKFb8sCl05HSzrWY7qCvlqBGY4wAL4kwNVKTO69d8F1x3++pLCHjyE8AXjKNNlt2BE5fCrxtbsu/BTsnLA==",
790
+ "version": "0.17.74-next.1",
791
+ "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.74-next.1.tgz",
792
+ "integrity": "sha512-nohxDatamx+tf/K6xGC+ZEh4DXMgLonjG+G45miIRS8QUL+WxVbP6VcCPBWCK+HfVGSQZAGmXztVfLpX1y+wug==",
793
793
  "license": "MIT",
794
794
  "bin": {
795
795
  "parley": "bin/parley.mjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.340-next.1",
3
+ "version": "0.2.342-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.",
@@ -46,7 +46,7 @@
46
46
  "@xterm/xterm": "^6.0.0",
47
47
  "clavarium-binder": "0.1.61-next.1",
48
48
  "clavarium-docket": "0.1.2-next.2",
49
- "clavarium-parley": "0.17.71-next.1",
49
+ "clavarium-parley": "0.17.74-next.1",
50
50
  "clavarium-tether": "0.1.0-next.54",
51
51
  "mammoth": "1.13.0",
52
52
  "mermaid": "11.17.2",
@@ -4,12 +4,19 @@
4
4
  * A key is a named USE ("home automation", "steering AI"), global to this
5
5
  * Clavarium, never tied to a person. It is a third kind of subject in the one
6
6
  * table of rights (grants.mjs, "apikey:<id>"): what it may do is lines of
7
- * that table, and a new key has none. Step 1 has one scope:
7
+ * that table, and a new key has none. Its scopes:
8
8
  *
9
9
  * status read the state: the server's memory, disk and CPU, the
10
10
  * conversations (their free name and state, never what they
11
11
  * say), the versions server:status r
12
12
  *
13
+ * a conversation, given ONE BY ONE (never "all, and those to come"):
14
+ * read read its chat conversation:<name> r
15
+ * talk and post a message in it, as the chat does,
16
+ * signed with the key's name, never as the person conversation:<name> rw
17
+ * A conversation archived takes its lines with it (devices.forget). Its
18
+ * terminal ("x") is never given to a key.
19
+ *
13
20
  * THE SECRET IS SHOWN ONCE. It is made here (32 random bytes, "clv_" before
14
21
  * them), given back by `create` and never again: only its sha256 is kept, as
15
22
  * a pairing's session is (devices.mjs). A 256-bit random secret needs no salt
@@ -30,12 +37,20 @@
30
37
  * makes a key.
31
38
  *
32
39
  * GET /api/apikeys {keys, scopes, defaultDays}
33
- * POST /api/apikeys {label, scopes, days|null} -> {key, secret}: the secret this once
40
+ * POST /api/apikeys {label, scopes, conversations: {name: 'read'|'talk'}, days|null}
41
+ * -> {key, secret}: the secret this once
42
+ * POST /api/apikeys/<id>/conversations {conversation, level: 'read'|'talk'|null}: one given, changed, taken back
34
43
  * POST /api/apikeys/<id>/revoke
35
44
  * GET /api/apikeys/<id>/journal its last uses
36
45
  *
37
- * GET /api/ext/v1/status Authorization: Bearer clv_... the state, as JSON
38
- * POST /api/ext/mcp the same, as one MCP tool (clavarium_status), JSON-RPC over HTTP
46
+ * Authorization: Bearer clv_... on each of these:
47
+ * GET /api/ext/v1/status the state, as JSON
48
+ * GET /api/ext/v1/conversations those it may read: {conversations: [{id, name, level, chat}]}
49
+ * GET /api/ext/v1/conversations/<name>/messages ?last=1..200 (50) | ?since=<cursor>: {chat, messages, cursor}
50
+ * POST /api/ext/v1/conversations/<name>/messages {text}: posted in its chat, signed with the key's name
51
+ * POST /api/ext/mcp the same as MCP tools (clavarium_status, clavarium_conversations,
52
+ * clavarium_read, clavarium_say), JSON-RPC over HTTP
53
+ * A conversation not given, or not there, is the same 403: a key learns nothing of what it was not given.
39
54
  *
40
55
  * The front lets /api/ext/ through without sign-on, as it does /c/
41
56
  * (deploy/install.sh, skip_auth_routes; deploy/updater.mjs for installs made
@@ -46,6 +61,7 @@ import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypt
46
61
  import { appendFileSync, readFileSync, writeFileSync, renameSync, statSync } from 'node:fs';
47
62
  import { Refusal } from './conversations.mjs';
48
63
  import { Grants, apiKeySubject } from './grants.mjs';
64
+ import { isConversationName } from './names.mjs';
49
65
 
50
66
  export const KEY_PREFIX = 'clv_';
51
67
  export const DEFAULT_DAYS = 90;
@@ -63,6 +79,13 @@ export const EXT_PREFIX = '/api/ext/';
63
79
 
64
80
  /* The scopes a key may be given: [asset, rights] in the table. */
65
81
  export const SCOPES = Object.freeze({ status: { asset: 'server:status', rights: 'r', label: 'Status (read)' } });
82
+ /* What a key may do in one conversation: [rights in the table]. */
83
+ export const LEVELS = Object.freeze({ read: 'r', talk: 'rw' });
84
+ export const levelOf = (rights) => (String(rights).includes('w') ? 'talk' : String(rights).includes('r') ? 'read' : null);
85
+ /* The messages one read gives, by default and at most. */
86
+ export const READ_DEFAULT = 50;
87
+ export const READ_MAX = 200;
88
+ export const SAY_MAX = 8000;
66
89
 
67
90
  const digest = (text) => createHash('sha256').update(text).digest();
68
91
  const oneLine = (value) => typeof value === 'string' && value.trim() !== '' && value.trim().length <= LABEL_MAX
@@ -70,18 +93,19 @@ const oneLine = (value) => typeof value === 'string' && value.trim() !== '' && v
70
93
  const SECRET = /^clv_[A-Za-z0-9_-]{43}$/;
71
94
 
72
95
  export class ApiKeys {
73
- #store; #grants; #now; #journal;
96
+ #store; #grants; #now; #journal; #exists;
74
97
  #used = new Map(); /* id -> { at, savedAt } */
75
98
  #calls = new Map(); /* id ('' for unknown keys) -> [times of the last minute] */
76
99
 
77
- constructor({ store, grants = new Grants(), journal = null, now = () => Date.now() }) {
78
- this.#store = store; this.#grants = grants; this.#journal = journal; this.#now = now;
100
+ /* `exists(name)`: whether a conversation is there (one is given only then). */
101
+ constructor({ store, grants = new Grants(), journal = null, now = () => Date.now(), exists = () => true }) {
102
+ this.#store = store; this.#grants = grants; this.#journal = journal; this.#now = now; this.#exists = exists;
79
103
  }
80
104
 
81
105
  #scopesOf(id) { return Object.entries(SCOPES).filter(([, s]) => this.#grants.can(apiKeySubject(id), s.asset, s.rights)).map(([name]) => name); }
82
106
  #shown(k) {
83
107
  const used = this.#used.get(k.name)?.at ?? k.usedAt ?? null;
84
- return { id: k.name, label: k.label, scopes: this.#scopesOf(k.name), createdBy: k.createdBy ?? null, createdAt: k.createdAt, expiresAt: k.expiresAt ?? null,
108
+ return { id: k.name, label: k.label, scopes: this.#scopesOf(k.name), conversations: this.conversationsOf(k.name), createdBy: k.createdBy ?? null, createdAt: k.createdAt, expiresAt: k.expiresAt ?? null,
85
109
  usedAt: used, expired: Boolean(k.expiresAt && Date.parse(k.expiresAt) <= this.#now()) };
86
110
  }
87
111
 
@@ -89,10 +113,33 @@ export class ApiKeys {
89
113
  list() { return this.#store.all().map((k) => this.#shown(k)).sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt))); }
90
114
  scopes() { return Object.entries(SCOPES).map(([id, s]) => ({ id, label: s.label })); }
91
115
 
92
- /* A new key: its secret is in the answer, this once. `days`: its life (null: it does not expire). */
93
- create({ label, scopes = [], days = DEFAULT_DAYS } = {}, who = '') {
116
+ /* The conversations a key was given, each with its level: [{ name, level }]. */
117
+ conversationsOf(id) {
118
+ return this.#grants.of(apiKeySubject(id), 'conversation').map((g) => ({ name: g.name, level: levelOf(g.rights) })).filter((c) => c.level)
119
+ .sort((a, b) => a.name.localeCompare(b.name));
120
+ }
121
+
122
+ #conversationAsked(name, level) {
123
+ if (!isConversationName(name) || !this.#exists(name)) throw new Refusal(404, 'No such conversation.');
124
+ if (level !== null && !Object.hasOwn(LEVELS, level)) throw new Refusal(400, `A conversation is given to read or to talk: ${Object.keys(LEVELS).join(', ')}.`);
125
+ }
126
+
127
+ /* One conversation given to a key, its level changed, or taken back (level null). */
128
+ setConversation(id, name, level) {
129
+ if (typeof id !== 'string' || !this.#store.get(id)) throw new Refusal(404, 'No such key.');
130
+ this.#conversationAsked(name, level);
131
+ if (level === null) this.#grants.take(apiKeySubject(id), `conversation:${name}`);
132
+ else this.#grants.give(apiKeySubject(id), `conversation:${name}`, LEVELS[level]);
133
+ return this.get(id);
134
+ }
135
+
136
+ /* A new key: its secret is in the answer, this once. `days`: its life (null: it does not expire).
137
+ `conversations`: { name: 'read' | 'talk' }, each named -- there is no "all". */
138
+ create({ label, scopes = [], conversations = {}, days = DEFAULT_DAYS } = {}, who = '') {
94
139
  if (!oneLine(label)) throw new Refusal(400, `A key has a name: one line, ${LABEL_MAX} characters at most.`);
95
140
  if (!Array.isArray(scopes) || scopes.some((s) => !Object.hasOwn(SCOPES, s))) throw new Refusal(400, `Scopes are among: ${Object.keys(SCOPES).join(', ')}.`);
141
+ if (!conversations || typeof conversations !== 'object' || Array.isArray(conversations)) throw new Refusal(400, 'Conversations are given by name: {name: "read" | "talk"}.');
142
+ for (const [name, level] of Object.entries(conversations)) this.#conversationAsked(name, level);
96
143
  if (days !== null && !(Number.isInteger(days) && days >= 1 && days <= DAYS_MAX)) throw new Refusal(400, `A key lasts 1 to ${DAYS_MAX} days, or does not expire.`);
97
144
  if (this.#store.all().length >= KEYS_MAX) throw new Refusal(409, `At most ${KEYS_MAX} keys: revoke one first.`);
98
145
  const name = label.trim();
@@ -104,6 +151,7 @@ export class ApiKeys {
104
151
  ...(who ? { createdBy: String(who).slice(0, 120) } : {}), expiresAt: days === null ? null : new Date(now + days * 86_400_000).toISOString() };
105
152
  this.#store.put(record);
106
153
  for (const s of new Set(scopes)) this.#grants.give(apiKeySubject(id), SCOPES[s].asset, SCOPES[s].rights);
154
+ for (const [name, level] of Object.entries(conversations)) if (level !== null) this.#grants.give(apiKeySubject(id), `conversation:${name}`, LEVELS[level]);
107
155
  return { key: this.#shown(record), secret };
108
156
  }
109
157
 
@@ -158,6 +206,18 @@ export class ApiKeys {
158
206
  /* Whether a key (already checked) has a scope. */
159
207
  may(id, scope) { return this.#scopesOf(id).includes(scope); }
160
208
 
209
+ /* Whether a key (already checked) may read ('read') or talk in ('talk') one conversation; throws 403
210
+ if not -- the same answer for a conversation not given and one that is not there. */
211
+ mayConversation(id, name, level = 'read') {
212
+ const rights = isConversationName(name) ? this.#grants.rightsOf(apiKeySubject(id), `conversation:${name}`) : '';
213
+ if (!rights.includes('r')) throw Object.assign(new Refusal(403, 'This key was not given this conversation.'), { key: id });
214
+ if (level === 'talk' && !rights.includes('w')) throw Object.assign(new Refusal(403, 'This key may read this conversation, not talk in it.'), { key: id });
215
+ return levelOf(rights);
216
+ }
217
+
218
+ /* Its name, as its messages are signed in a chat (Parley's "by"). */
219
+ signature(id) { const k = this.#store.get(id); return k ? { id: apiKeySubject(id), name: k.label, kind: 'ai', place: 'API key' } : null; }
220
+
161
221
  #seen(id) {
162
222
  const now = this.#now();
163
223
  const u = this.#used.get(id) ?? { at: null, savedAt: 0 };
@@ -228,8 +288,35 @@ export async function statusOf({ conversations, talk, health, answerer, capacity
228
288
 
229
289
  /* ---- the door for programs: /api/ext/ ---- */
230
290
 
291
+ /* A CONVERSATION'S THREAD as a key reads it: the messages of the person and of the AI, field by field --
292
+ its words, who said it, when; a file by its name only. Never the machine's own lines, a path, nor
293
+ anything the page keeps for itself. `read`: what talk.of gives. */
294
+ const TEXT_MAX = 20_000;
295
+ const fileName = (p) => String(p ?? '').split('/').filter(Boolean).at(-1)?.slice(0, 120) ?? '';
296
+ export function threadOf(read) {
297
+ if (!read?.on) return { chat: false, messages: [], cursor: null };
298
+ const messages = (Array.isArray(read.messages) ? read.messages : []).filter((m) => m && (m.from === 'person' || m.from === 'agent')).map((m) => {
299
+ const files = [...(Array.isArray(m.files) ? m.files.map((f) => fileName(f?.name || f?.path)) : []), ...(m.kind === 'show' && m.path ? [fileName(m.path)] : [])].filter(Boolean).slice(0, 12);
300
+ const choices = Array.isArray(m.choices) ? m.choices.filter((c) => typeof c === 'string').slice(0, 8).map((c) => c.slice(0, 200)) : [];
301
+ return { id: String(m.id ?? '').slice(0, 80), at: String(m.at ?? '').slice(0, 40), from: m.from, kind: String(m.kind ?? 'say').slice(0, 20),
302
+ text: typeof m.text === 'string' ? m.text.slice(0, TEXT_MAX) : '', ...(typeof m.by?.name === 'string' && m.by.name ? { by: m.by.name.slice(0, 80) } : {}),
303
+ ...(choices.length ? { choices } : {}), ...(files.length ? { files } : {}) };
304
+ });
305
+ return { chat: true, messages, cursor: typeof read.cursor === 'string' ? read.cursor : null };
306
+ }
307
+
308
+ /* What a read asks for: the newest `last` (READ_DEFAULT; READ_MAX at most), or what came `since` a cursor. */
309
+ export function readPart(get) {
310
+ const last = Number(get('last') ?? READ_DEFAULT);
311
+ const since = get('since');
312
+ if (!Number.isInteger(last) || last < 1 || last > READ_MAX) throw new Refusal(400, `last: 1 to ${READ_MAX}.`);
313
+ if (since !== null && since !== undefined && (typeof since !== 'string' || !/^[0-9A-Za-z.~-]{1,80}$/.test(since))) throw new Refusal(400, 'since: a cursor given by a read before.');
314
+ return { last: String(last), ...(since ? { since } : {}) };
315
+ }
316
+
231
317
  const MCP_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
232
318
  const MCP_BODY_MAX = 64 * 1024;
319
+ const CONVERSATION_ARG = { type: 'string', description: 'The conversation\'s id, as clavarium_conversations gives it.' };
233
320
  export const STATUS_TOOL = {
234
321
  name: 'clavarium_status',
235
322
  title: 'Clavarium status',
@@ -237,12 +324,36 @@ export const STATUS_TOOL = {
237
324
  inputSchema: { type: 'object', properties: {}, additionalProperties: false },
238
325
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
239
326
  };
327
+ export const CONVERSATIONS_TOOL = {
328
+ name: 'clavarium_conversations',
329
+ title: 'Conversations of this key',
330
+ description: 'The conversations this key was given, each with its id, name, level (read or talk) and whether its chat is on.',
331
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
332
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
333
+ };
334
+ export const READ_TOOL = {
335
+ name: 'clavarium_read',
336
+ title: 'Read a conversation',
337
+ description: `The newest messages of one conversation's chat (person and AI), oldest first, with a cursor; give the cursor back as "since" for only what came after. ${READ_DEFAULT} by default, ${READ_MAX} at most.`,
338
+ inputSchema: { type: 'object', properties: { conversation: CONVERSATION_ARG, last: { type: 'integer', minimum: 1, maximum: READ_MAX }, since: { type: 'string' } }, required: ['conversation'], additionalProperties: false },
339
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
340
+ };
341
+ export const SAY_TOOL = {
342
+ name: 'clavarium_say',
343
+ title: 'Post a message in a conversation',
344
+ description: 'Post a message in one conversation\'s chat, as the person would; it is shown signed with this key\'s name. The conversation must have been given to this key to talk.',
345
+ inputSchema: { type: 'object', properties: { conversation: CONVERSATION_ARG, text: { type: 'string', minLength: 1, maxLength: SAY_MAX } }, required: ['conversation', 'text'], additionalProperties: false },
346
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
347
+ };
348
+ export const TOOLS = [STATUS_TOOL, CONVERSATIONS_TOOL, READ_TOOL, SAY_TOOL];
240
349
 
241
350
  /* Returns true when the request was under /api/ext/ (answered here). `status()`: the state, as statusOf
242
- makes it. `originOk(headers)`: whether an Origin is this site's (gate.mjs); a call from a page of
243
- another site is refused. */
244
- export async function handleExternal(request, response, { keys, status, headers = {}, originOk = () => false, version = null }) {
245
- const { pathname } = new URL(request.url ?? '/', 'http://local');
351
+ makes it. `chats`: { list() -> [{ id, name }], read(name, part) -> talk.of's answer, chatOn(name),
352
+ say(name, text, by) -> { told } }. `originOk(headers)`: whether an Origin is this site's (gate.mjs); a
353
+ call from a page of another site is refused. */
354
+ export async function handleExternal(request, response, { keys, status, chats = null, headers = {}, originOk = () => false, version = null }) {
355
+ const url = new URL(request.url ?? '/', 'http://local');
356
+ const { pathname } = url;
246
357
  if (!pathname.startsWith(EXT_PREFIX) && pathname !== EXT_PREFIX.slice(0, -1)) return false;
247
358
  const route = pathname.slice(EXT_PREFIX.length - 1);
248
359
  const send = (code, body, more = {}) => {
@@ -260,6 +371,30 @@ export async function handleExternal(request, response, { keys, status, headers
260
371
  const more = error.status === 401 ? { 'www-authenticate': 'Bearer realm="clavarium"' } : error.status === 429 ? { 'retry-after': String(error.retry ?? 60) } : {};
261
372
  return send(error.status, { error: error.message }, more);
262
373
  };
374
+ const bodyOf = async (max) => {
375
+ let text = '';
376
+ for await (const piece of request) { text += piece; if (text.length > max) throw new Refusal(413, 'Too long.'); }
377
+ return text;
378
+ };
379
+ /* What a key does with conversations, the same for the API and MCP. Each throws a Refusal. */
380
+ const given = (id) => keys.conversationsOf(id);
381
+ const listed = (id) => {
382
+ const names = new Map((chats?.list() ?? []).map((c) => [c.id, c.name]));
383
+ return { conversations: given(id).filter((c) => names.has(c.name)).map((c) => ({ id: c.name, name: names.get(c.name), level: c.level, chat: Boolean(chats?.chatOn(c.name)) })) };
384
+ };
385
+ const known = (name) => { if (!(chats?.list() ?? []).some((c) => c.id === name)) throw new Refusal(403, 'This key was not given this conversation.'); };
386
+ const reading = (id, name, part) => {
387
+ keys.mayConversation(id, name, 'read'); known(name);
388
+ return threadOf(chats.read(name, part));
389
+ };
390
+ const saying = async (id, name, text) => {
391
+ keys.mayConversation(id, name, 'talk'); known(name);
392
+ if (typeof text !== 'string' || !text.trim()) throw new Refusal(400, 'Say something: text.');
393
+ if (text.length > SAY_MAX) throw new Refusal(400, `${SAY_MAX} characters at most.`);
394
+ const said = await chats.say(name, text, keys.signature(id));
395
+ return { ok: true, told: typeof said?.told === 'string' ? said.told : null };
396
+ };
397
+ const ownError = (error, id) => (error instanceof Refusal ? Object.assign(error, { key: error.key ?? id }) : error);
263
398
  try {
264
399
  if (route === '/v1/status') {
265
400
  if (request.method !== 'GET') return send(405, { error: 'Call this address with GET.' }, { allow: 'GET' });
@@ -269,6 +404,25 @@ export async function handleExternal(request, response, { keys, status, headers
269
404
  note(id, 200);
270
405
  return send(200, body);
271
406
  }
407
+ const one = /^\/v1\/conversations(?:\/([^/]+)\/messages)?$/.exec(route);
408
+ if (one) {
409
+ const allowed = one[1] ? 'GET, POST' : 'GET';
410
+ if (!allowed.split(', ').includes(request.method)) return send(405, { error: `Call this address with ${allowed}.` }, { allow: allowed });
411
+ let id;
412
+ try { id = keys.check(request.headers.authorization); } catch (error) { return refused(error); }
413
+ try {
414
+ if (!one[1]) { const body = listed(id); note(id, 200); return send(200, body); }
415
+ let name;
416
+ try { name = decodeURIComponent(one[1]); } catch { name = ''; }
417
+ if (request.method === 'GET') { const body = reading(id, name, readPart((k) => url.searchParams.get(k))); note(id, 200); return send(200, body); }
418
+ if (!String(request.headers['content-type'] ?? '').startsWith('application/json')) throw new Refusal(415, 'Send JSON: {"text": "..."}.');
419
+ let body;
420
+ try { body = JSON.parse(await bodyOf(SAY_MAX * 4 + 1024)); } catch (error) { if (error instanceof Refusal) throw error; throw new Refusal(400, 'The request is not JSON.'); }
421
+ const done = await saying(id, name, body?.text);
422
+ note(id, 201);
423
+ return send(201, done);
424
+ } catch (error) { return refused(ownError(error, id)); }
425
+ }
272
426
  if (route === '/mcp') {
273
427
  if (request.method !== 'POST') return send(405, { error: 'MCP is spoken with POST here (no event stream).' }, { allow: 'POST' });
274
428
  let id;
@@ -280,35 +434,53 @@ export async function handleExternal(request, response, { keys, status, headers
280
434
  if (!msg || typeof msg !== 'object' || Array.isArray(msg) || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
281
435
  note(id, 400, '/mcp'); return send(400, { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request' } });
282
436
  }
283
- const what = `/mcp ${msg.method.slice(0, 40)}${msg.method === 'tools/call' ? ` ${String(msg.params?.name ?? '').slice(0, 40)}` : ''}`;
437
+ const args = msg.params?.arguments && typeof msg.params.arguments === 'object' && !Array.isArray(msg.params.arguments) ? msg.params.arguments : {};
438
+ /* The journal says which tool, and on which conversation. */
439
+ const what = `/mcp ${msg.method.slice(0, 40)}${msg.method === 'tools/call' ? ` ${String(msg.params?.name ?? '').slice(0, 40)}${typeof args.conversation === 'string' ? ` ${args.conversation.slice(0, 32)}` : ''}` : ''}`;
284
440
  /* A notification (no id) is taken, never answered. */
285
441
  if (msg.id === undefined || msg.id === null) { note(id, 202, what); response.writeHead(202, { ...headers, 'cache-control': 'no-store' }).end(); return true; }
286
- const answer = (result) => { note(id, 200, what); return send(200, { jsonrpc: '2.0', id: msg.id, result }); };
442
+ const answer = (result, code = 200) => { note(id, code, what); return send(200, { jsonrpc: '2.0', id: msg.id, result }); };
287
443
  const fail = (code, message, http = 200) => { note(id, http === 200 ? 400 : http, what); return send(http, { jsonrpc: '2.0', id: msg.id, error: { code, message } }); };
444
+ const result = (body) => answer({ content: [{ type: 'text', text: JSON.stringify(body) }], structuredContent: body, isError: false });
288
445
  switch (msg.method) {
289
446
  case 'initialize': {
290
447
  const asked = String(msg.params?.protocolVersion ?? '');
291
448
  return answer({ protocolVersion: MCP_VERSIONS.includes(asked) ? asked : MCP_VERSIONS[0], capabilities: { tools: { listChanged: false } },
292
- serverInfo: { name: 'clavarium', title: 'Clavarium', version: version ?? '0' }, instructions: 'Read-only state of this Clavarium. One tool: clavarium_status.' });
449
+ serverInfo: { name: 'clavarium', title: 'Clavarium', version: version ?? '0' },
450
+ instructions: 'This Clavarium, as far as this key was given it: its state (clavarium_status), the conversations given to it (clavarium_conversations), to read (clavarium_read) or to talk in (clavarium_say).' });
293
451
  }
294
452
  case 'ping': return answer({});
295
- case 'tools/list': return answer({ tools: [STATUS_TOOL] });
453
+ case 'tools/list': return answer({ tools: TOOLS });
296
454
  case 'tools/call': {
297
- if (msg.params?.name !== STATUS_TOOL.name) return fail(-32602, `Unknown tool: ${String(msg.params?.name ?? '').slice(0, 60)}`);
298
- if (!keys.may(id, 'status')) {
299
- note(id, 403, what);
300
- return send(403, { jsonrpc: '2.0', id: msg.id, error: { code: -32001, message: `This key was not given the scope "${SCOPES.status.label}".` } });
455
+ const name = msg.params?.name;
456
+ if (!TOOLS.some((x) => x.name === name)) return fail(-32602, `Unknown tool: ${String(name ?? '').slice(0, 60)}`);
457
+ try {
458
+ if (name === STATUS_TOOL.name) {
459
+ if (!keys.may(id, 'status')) throw new Refusal(403, `This key was not given the scope "${SCOPES.status.label}".`);
460
+ return result(await status());
461
+ }
462
+ if (name === CONVERSATIONS_TOOL.name) return result(listed(id));
463
+ if (typeof args.conversation !== 'string') return fail(-32602, 'conversation: the id of a conversation.');
464
+ if (name === READ_TOOL.name) return result(reading(id, args.conversation, readPart((k) => (args[k] === undefined ? null : typeof args[k] === 'number' ? String(args[k]) : args[k]))));
465
+ const done = await saying(id, args.conversation, args.text);
466
+ note(id, 201, what);
467
+ return send(200, { jsonrpc: '2.0', id: msg.id, result: { content: [{ type: 'text', text: JSON.stringify(done) }], structuredContent: done, isError: false } });
468
+ } catch (error) {
469
+ if (!(error instanceof Refusal)) throw error;
470
+ /* Not given: refused as the API refuses it. Anything else is the tool's own failure, said to the caller. */
471
+ if (error.status === 403) { note(id, 403, what); return send(403, { jsonrpc: '2.0', id: msg.id, error: { code: -32001, message: error.message } }); }
472
+ note(id, error.status, what);
473
+ return send(200, { jsonrpc: '2.0', id: msg.id, result: { content: [{ type: 'text', text: error.message }], isError: true } });
301
474
  }
302
- const body = await status();
303
- return answer({ content: [{ type: 'text', text: JSON.stringify(body) }], structuredContent: body, isError: false });
304
475
  }
305
476
  default: return fail(-32601, 'Method not found');
306
477
  }
307
478
  }
308
479
  note(null, 404);
309
- return send(404, { error: 'Not found. GET /api/ext/v1/status, or MCP at /api/ext/mcp.' });
480
+ return send(404, { error: 'Not found. GET /api/ext/v1/status, /api/ext/v1/conversations, or MCP at /api/ext/mcp.' });
310
481
  } catch (error) {
311
482
  if (error instanceof Refusal) return refused(error);
483
+ note(null, 500);
312
484
  return send(500, { error: 'Something failed on the server.' });
313
485
  }
314
486
  }
@@ -326,16 +498,24 @@ export async function handleApiKeys(request, response, keys, originOk, headers =
326
498
  if (request.method !== 'POST') return false;
327
499
  if (!originOk(request.headers) || !String(request.headers['content-type'] ?? '').startsWith('application/json')) return send(403, { error: 'This request does not come from this site.' });
328
500
  let text = '';
329
- for await (const piece of request) { text += piece; if (text.length > 4096) return send(413, { error: 'Too long.' }); }
501
+ for await (const piece of request) { text += piece; if (text.length > 16_384) return send(413, { error: 'Too long.' }); }
330
502
  let body;
331
503
  try { body = text ? JSON.parse(text) : {}; } catch { return send(400, { error: 'The request is not JSON.' }); }
332
504
  if (!body || typeof body !== 'object') body = {};
333
505
  if (pathname === '/api/apikeys') {
334
- const made = keys.create({ label: body.label, scopes: body.scopes ?? [], days: body.days === undefined ? DEFAULT_DAYS : body.days }, who);
506
+ const made = keys.create({ label: body.label, scopes: body.scopes ?? [], conversations: body.conversations ?? {}, days: body.days === undefined ? DEFAULT_DAYS : body.days }, who);
335
507
  /* Its name and scopes; never the secret. */
336
- events?.add({ kind: 'access', text: `API key "${made.key.label}" made${made.key.scopes.length ? ` (${made.key.scopes.join(', ')})` : ' (no scope)'}`, who: who || null });
508
+ const what = [...made.key.scopes, ...made.key.conversations.map((c) => `${c.name} ${c.level}`)];
509
+ events?.add({ kind: 'access', text: `API key "${made.key.label}" made${what.length ? ` (${what.join(', ')})` : ' (no scope)'}`, who: who || null });
337
510
  return send(201, made);
338
511
  }
512
+ const giving = /^\/api\/apikeys\/([0-9a-f-]{36})\/conversations$/.exec(pathname);
513
+ if (giving) {
514
+ const level = body.level === undefined ? null : body.level;
515
+ const key = keys.setConversation(giving[1], body.conversation, level);
516
+ events?.add({ kind: 'access', text: `API key "${key.label}": ${body.conversation} ${level ?? 'taken back'}`, who: who || null });
517
+ return send(200, { key });
518
+ }
339
519
  const revoke = /^\/api\/apikeys\/([0-9a-f-]{36})\/revoke$/.exec(pathname);
340
520
  if (revoke) {
341
521
  const label = keys.get(revoke[1])?.label;
@@ -86,6 +86,12 @@ export function demandeView(q) {
86
86
  if (where) sub.push(where);
87
87
  if (c.body) { sub.push(count(String(c.body).split('\n').length, 'req-lines')); v.quote = plain(c.body); }
88
88
  if (c.files?.length) sub.push(count(c.files.length, 'req-attachments'));
89
+ /* The mail it answers, forwards or acts on (Tether's about.ref, 06-11): a chip under the title, « en réponse à
90
+ ✉ Subject · sender », opened in the mail viewer (Parley's `re`, app.js openMailRef) -- read only when tapped. */
91
+ if (typeof about.ref === 'string' && about.ref.startsWith('mail:') && ['reply', 'forward', 'move', 'flag', 'delete'].includes(c.action)) {
92
+ v.re = { ref: about.ref, label: about.subject ? String(about.subject) : w('req-a-message'), ...(about.from ? { note: nameOfAddr(about.from) } : {}),
93
+ ...(c.action === 'reply' ? {} : { lead: w(c.action === 'forward' ? 'request-re-forward' : 'request-re-mail') }) };
94
+ }
89
95
  } else if (c.kind === 'calendar') {
90
96
  const answer = { accept: 'accept', yes: 'accept', decline: 'decline', no: 'decline', refuse: 'decline', tentative: 'maybe', maybe: 'maybe' }[String(c.answer ?? '').toLowerCase()] ?? '';
91
97
  const was = c.action === 'create' ? null : about;
@@ -150,7 +156,7 @@ export function demandeView(q) {
150
156
  kind, title: v.title || (q?.verb ? String(q.verb) : w('req-a-request')), sub: sub.filter(Boolean).slice(0, 3),
151
157
  ...(v.risk.length ? { risk: v.risk } : {}), ...(v.facts.length ? { facts: v.facts } : {}),
152
158
  ...(v.before ? { before: v.before, after: v.after } : {}),
153
- ...(v.quote ? { quote: v.quote } : {}), ...(v.code ? { code: v.code } : {}),
159
+ ...(v.quote ? { quote: v.quote } : {}), ...(v.code ? { code: v.code } : {}), ...(v.re ? { re: v.re } : {}),
154
160
  ...(q?.why ? { why: String(q.why) } : {}),
155
161
  /* The technical line, in "See all" only. */
156
162
  detail: [q?.verb, q?.detail].filter(Boolean).join(' — '),
package/server/grants.mjs CHANGED
@@ -27,8 +27,10 @@
27
27
  * in the table: the owner may do everything, always.
28
28
  *
29
29
  * An API key is not a device and not a conversation: it is given only what
30
- * its scopes name ("server:status", read), never a secret, a conversation or
31
- * a folder in this version; and nothing else is ever given "server:".
30
+ * its scopes name -- "server:status" (read), and conversations one by one,
31
+ * their chat to read ("r") or to talk in ("rw"), never their terminal ("x")
32
+ * -- never a secret nor a folder in this version; and nothing else is ever
33
+ * given "server:".
32
34
  *
33
35
  * No groups, no inheritance. One rule sits on top, in the door: whoever was
34
36
  * given a conversation, its terminal or its chat, sees the files of that
@@ -92,9 +94,12 @@ export class Grants {
92
94
  /* A secret is handed to a conversation, never to a device: a device
93
95
  would be a way to read it. */
94
96
  if (typeOf(asset) === 'secret' && !subject.startsWith('conversation:')) throw new Refusal(400, 'A secret is handed to a conversation, never shared with a device.');
95
- if (typeOf(asset) === 'conversation' && !subject.startsWith('pairing:')) throw new Refusal(400, 'A conversation is shared with a device, not with another conversation.');
96
- /* The state of the server is given to an API key, and an API key is given nothing else (yet). */
97
- if ((typeOf(asset) === 'server') !== subject.startsWith('apikey:')) throw new Refusal(400, 'An API key is given the state of the server, and only that.');
97
+ if (typeOf(asset) === 'conversation' && !subject.startsWith('pairing:') && !subject.startsWith('apikey:')) throw new Refusal(400, 'A conversation is shared with a device or an API key, not with another conversation.');
98
+ /* The state of the server is given to an API key only; an API key is given only that, and
99
+ conversations one by one -- their chat, to read or to write in, never their terminal. */
100
+ if (typeOf(asset) === 'server' && !subject.startsWith('apikey:')) throw new Refusal(400, 'The state of the server is given to an API key only.');
101
+ if (subject.startsWith('apikey:') && !['server', 'conversation'].includes(typeOf(asset))) throw new Refusal(400, 'An API key is given the state of the server and conversations, nothing else.');
102
+ if (subject.startsWith('apikey:') && clean.includes('x')) throw new Refusal(400, 'An API key reads a conversation or talks in it, never uses its terminal.');
98
103
  this.#store.put({ name: this.#key(subject, asset), subject, asset, rights: clean });
99
104
  return clean;
100
105
  }
package/server/guide.mjs CHANGED
@@ -119,6 +119,8 @@ export function ownText({ name, tool, workKept, resources = [], chat, online, se
119
119
  : '- Chat with the person: on. Parley is installed: run parley guide. When you were given Parley as your own tools (MCP: tell, ask, doing, status...), use them to talk to the person, and say with doing what you do at each new step; the parley command does the same.');
120
120
  /* How Parley is used is Parley's to say (parley guide); what is here is this chat's: it renders Markdown. */
121
121
  if (chat) out.push('- The chat shows Markdown (lists, tables, "> [!IMPORTANT]") and pictures of /work: ![before](/work/a.png).');
122
+ /* A mail cited by its reference (06-11): a chip the person opens in the mail viewer (Parley's schemes, app.js openMailRef). */
123
+ if (chat) out.push('- To cite a mail, write [its subject](mail:REF) with the ref Tether gives (ref: mail:...), copied whole: the person opens it with a tap.');
122
124
  /* The thread is kept whole: after a restart, its end is read, and further back on demand. */
123
125
  if (chat && reread) out.push(`- After a restart: ${plain(reread, 60)}, the end of the chat; it says how to read further back.`);
124
126
  /* 02-11: the one command a tool may ask of the server. */
package/server/main.mjs CHANGED
@@ -232,7 +232,7 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
232
232
  /* THE DOOR FOR PROGRAMS (apikeys.mjs): an API key is the right, never the gate -- the front lets
233
233
  /api/ext/ through without sign-on, and strips the identity headers there. */
234
234
  if (apikeys && (pathname === '/api/ext' || pathname.startsWith('/api/ext/'))) {
235
- await handleExternal(request, response, { keys: apikeys.keys, status: apikeys.status, headers: HEADERS, originOk, version: platform?.version ?? null });
235
+ await handleExternal(request, response, { keys: apikeys.keys, status: apikeys.status, chats: apikeys.chats, headers: HEADERS, originOk, version: platform?.version ?? null });
236
236
  return;
237
237
  }
238
238
  if (door && pathname.startsWith('/c/')) {
@@ -693,10 +693,18 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
693
693
  for (const name of ['clavarium-parley', 'clavarium-tether', 'clavarium-binder', 'clavarium-docket']) {
694
694
  try { components[name.slice('clavarium-'.length)] = JSON.parse(readFileSync(packageFile(name, 'package.json'), 'utf8')).version; } catch { /* not installed here */ }
695
695
  }
696
- const apiKeys = new ApiKeys({ store: new Store(`${dataDir}/apikeys.json`), grants, journal: `${dataDir}/apikeys.log` });
696
+ const apiKeys = new ApiKeys({ store: new Store(`${dataDir}/apikeys.json`), grants, journal: `${dataDir}/apikeys.log`, exists: (name) => all.list().some((c) => c.name === name) });
697
697
  /* What the host program says of the server is never waited for long: a key gets what is known. */
698
698
  const briefly = { brief: () => quick(capacity.brief(), 3000, null), room: () => quick(capacity.room(), 3000, null) };
699
- const apikeys = { keys: apiKeys, status: () => statusOf({ conversations: all, talk, health, answerer, capacity: briefly, history, platform, updates, components }) };
699
+ const apikeys = { keys: apiKeys, status: () => statusOf({ conversations: all, talk, health, answerer, capacity: briefly, history, platform, updates, components }),
700
+ /* A key's conversations (their chat, through talk.mjs): read as the page reads it; a message posted as the page
701
+ posts one (its secrets lifted the same way), signed with the key's name. */
702
+ chats: {
703
+ list: () => all.list().map((c) => ({ id: c.name, name: typeof c.title === 'string' && c.title ? c.title : c.name })),
704
+ chatOn: (name) => { try { return talk.of(name, { state: '1' }).on === true; } catch { return false; } },
705
+ read: (name, part) => talk.of(name, part),
706
+ say: (name, text, by) => talk.say(name, text, undefined, [], undefined, { by }),
707
+ } };
700
708
  const features = new Features({ file: new JsonFile(`${dataDir}/features.json`, {}), context: async () => ({
701
709
  secrets: secrets.list(), dictation: voice.about(), boxes: boxes.all(), alerts: alerts.about().devices.length,
702
710
  conversations: all.list().map((c) => ({ tool: c.tool })), tools: all.tools().map((t) => t.id),
@@ -64,5 +64,8 @@ export const SETTINGS_WORDS_FR = {
64
64
  'set-apikeys-no-scope': 'Aucune portée', 'set-apikeys-by-you': 'par vous', 'set-apikeys-used': 'Utilisée {when}', 'set-apikeys-unused': 'Jamais utilisée',
65
65
  'set-apikeys-expired': 'Expirée', 'set-apikeys-expires-on': 'Expire le {date}', 'set-apikeys-no-expiry': 'N\'expire pas',
66
66
  'set-apikeys-created': 'Créée le {date}', 'set-apikeys-revoke': 'Révoquer', 'set-apikeys-revoke-q': 'Révoquer maintenant ?',
67
+ 'set-apikeys-convs': 'Conversations', 'set-apikeys-convs-hint': 'Une par une : lire ou parler', 'set-apikeys-off': 'Non',
68
+ 'set-apikeys-read': 'Lire', 'set-apikeys-talk': 'Parler', 'set-apikeys-no-convs': 'Aucune conversation pour l\'instant',
69
+ 'set-apikeys-journal': 'Journal', 'set-apikeys-no-use': 'Aucun appel pour l\'instant',
67
70
  };
68
71
  export const settingsWords = (lang) => (String(lang ?? '').toLowerCase().split('-')[0] === 'fr' ? { ...SETTINGS_WORDS_FR } : {});
package/server/talk.mjs CHANGED
@@ -595,7 +595,7 @@ export class Talk {
595
595
  Only where the chat is on; never counted as unread (the page counts
596
596
  the tool's messages only); at most SYSTEM_MAX kept. Resolves with the
597
597
  line kept, or null. `actions`: ids the page maps to buttons. */
598
- event(name, { kind, text, level, tone, topic, brief, actions = [], request, outcome } = {}) {
598
+ event(name, { kind, text, level, tone, topic, brief, actions = [], request, outcome, re } = {}) {
599
599
  if (!Object.hasOwn(EVENT_LEVELS, kind)) throw new RangeError(`No such kind of event: ${kind}`);
600
600
  const said = lineSaid(text, EVENT_TEXT_MAX);
601
601
  if (said === null) return null;
@@ -614,6 +614,8 @@ export class Talk {
614
614
  actions: (Array.isArray(actions) ? actions : []).filter((a) => typeof a === 'string' && ACTION.test(a)).slice(0, ACTIONS_MAX),
615
615
  /* A request's card, as Parley draws it (demandes.mjs): plain data, bounded. */
616
616
  ...(request && typeof request === 'object' && !Array.isArray(request) && JSON.stringify(request).length <= REQUEST_MAX ? { request } : {}),
617
+ /* What it is about (Parley's `re`, 06-11): the mail that came back, a chip after its text. */
618
+ ...(re && typeof re === 'object' && typeof re.ref === 'string' && re.ref.length <= 2000 && JSON.stringify(re).length <= 4000 ? { re } : {}),
617
619
  /* How the call a line closes ended (tether-done): yes, always, no, timeout, withdrawn, stopped. */
618
620
  ...(OUTCOMES.includes(outcome) ? { outcome } : {}),
619
621
  };
@@ -21,6 +21,7 @@
21
21
  */
22
22
  import { mkdirSync, lstatSync } from 'node:fs';
23
23
  import { keeper } from 'clavarium-tether/host';
24
+ import { mailRef } from 'clavarium-tether/verbs';
24
25
  import { JsonFile } from './store.mjs';
25
26
  import { demandeView } from './demandes.mjs';
26
27
 
@@ -85,6 +86,18 @@ export function noticeLine(kind, target, text) {
85
86
  return head;
86
87
  }
87
88
 
89
+ /* THE MAIL A NOTICE IS ABOUT (06-11): a mail that came back, or is delayed, carries the Message-ID of the mail sent
90
+ (`ref`); with its mailbox, that is a reference (mail:TARGET/ID) the line shows as a chip (Parley's `re`), opened in
91
+ the mail viewer -- its subject, from Tether's sentence, as the chip's label. Other notices: none. */
92
+ const NOTICE_MAILS = new Set(['mail.bounced', 'mail.delayed']);
93
+ export function noticeRe(kind, targetId, messageId, text) {
94
+ if (!NOTICE_MAILS.has(kind) || !targetId || !messageId) return null;
95
+ const ref = mailRef(String(targetId), String(messageId));
96
+ if (!ref) return null;
97
+ const subject = /\bmail "([^"\n]{1,200})"/.exec(String(text ?? ''))?.[1]?.trim();
98
+ return { ref, label: subject || { k: 'req-a-message', t: 'a message' }, lead: { k: 'line-re-sent', t: 'the mail sent' } };
99
+ }
100
+
88
101
  export class Tethers {
89
102
  #keeper; #resources; #conversations; #secrets; #dockets; #timers = []; #changes = 0; #seen = new Map(); #offered; #noticed; #ended = new Map(); #acting = [];
90
103
  /* Set by the server once the thread is ready (main.mjs): (name, event) => talk.event(...).
@@ -205,7 +218,8 @@ export class Tethers {
205
218
  /* Clavarium's head and frame in the reader's words; Tether's own sentence as Tether wrote it. */
206
219
  const line = noticeLine(kind, n.target?.title ? String(n.target.title) : '', String(n.text ?? '').trim());
207
220
  const text = line.t;
208
- try { this.announce?.(name, { kind: 'tether-notice', text: line, topic: TOPIC_NOTICE, ...(warns ? { tone: 'warn', level: 'needs-you' } : {}) }); } catch { /* its chat is off */ }
221
+ const re = noticeRe(kind, n.target?.id, n.ref, n.text);
222
+ try { this.announce?.(name, { kind: 'tether-notice', text: line, topic: TOPIC_NOTICE, ...(warns ? { tone: 'warn', level: 'needs-you' } : {}), ...(re ? { re } : {}) }); } catch { /* its chat is off */ }
209
223
  try {
210
224
  if (this.#dockets?.on(name)) {
211
225
  this.#dockets.post(name, { kind: 'tether-notice', text: `${text}${/[.!?]$/.test(text) ? '' : '.'} See more: tether notices.`,
package/web/app.js CHANGED
@@ -2998,6 +2998,9 @@
2998
2998
  label: (ref) => (/^file:\/(work|resources)\//.test(ref) ? 'Open' : null),
2999
2999
  open: (ref) => { const m = /^file:\/(work|resources\/[^/]+)\/(.+)$/.exec(ref); if (!m) return; const tab = m[1] === 'work' ? 'work' : m[1].slice('resources/'.length); void openFromChat(tab, m[2]); },
3000
3000
  },
3001
+ /* A mail it cites ([Subject](mail:TARGET/ID), Parley's schemes), what a request answers, the mail that came back:
3002
+ a chip that opens the mail viewer, read when tapped, by whoever may read that mailbox (else the viewer says so). */
3003
+ schemes: { mail: { icon: 'mail', open: (ref, label) => { void openMailRef(ref, { label, of: name }); } } },
3001
3004
  /* A reaction to one of its messages: wherever the chat may be written in. */
3002
3005
  ...(!DEVICE || deviceParts.chat === 'write' ? { react: (to, reaction) => post(talkPath(name, '/react'), { to, reaction }) } : {}),
3003
3006
  /* A message attached to a card (#180), from its menu: its id, as the card opens it again. */
@@ -4827,7 +4830,9 @@
4827
4830
  for (const q of approvals) {
4828
4831
  if (!q.view) continue;
4829
4832
  const view = withWho && q.agent?.name ? { ...q.view, sub: [q.agent.name, ...(Array.isArray(q.view.sub) ? q.view.sub : [q.view.sub])].filter(Boolean) } : q.view;
4830
- box.append(P.requestCard(view, { act, words, steps: cardSteps, host: document.body }));
4833
+ /* The mail it answers (its `re`): opened in the mail viewer, Reply writing in the chat of the conversation that asks. */
4834
+ const schemes = { mail: { icon: 'mail', open: (ref, label) => { void openMailRef(ref, { label, of: String(q.agent?.id ?? '').startsWith('conversation:') ? q.agent.id.slice('conversation:'.length) : current }); } } };
4835
+ box.append(P.requestCard(view, { act, words, steps: cardSteps, host: document.body, schemes }));
4831
4836
  }
4832
4837
  });
4833
4838
  return box;
@@ -5336,6 +5341,8 @@
5336
5341
  $('salon-thread').dataset.theme = document.documentElement.dataset.theme === 'light' ? 'light' : 'dark';
5337
5342
  salonThread = mount($('salon-thread'), {
5338
5343
  words, markdown: true, agentName: '',
5344
+ /* A mail an AI of the room cites: the same chip and viewer as in a conversation's chat. */
5345
+ schemes: { mail: { icon: 'mail', open: (ref, label) => { void openMailRef(ref, { label }); } } },
5339
5346
  load: (asked = {}) => fetch(`${API}/rooms/${id}/talk${asked.last ? `?last=${asked.last}` : ''}`).then((x) => x.json()).then((d) => {
5340
5347
  /* Who was given a message and has not answered yet (#282): « Hugo réfléchit… ». */
5341
5348
  const who = thinkingOf(d);
@@ -6146,6 +6153,36 @@
6146
6153
  scope until one is ticked; its secret shown this once, then never; revoked at once, confirmed in place.
6147
6154
  Administrators only: hidden on a device, and where the server does not answer it. */
6148
6155
  const shortDate = (t) => new Date(t).toLocaleDateString([], { day: 'numeric', month: 'short', year: 'numeric' });
6156
+ /* Its conversations, one by one (step 2): each Off / Read / Talk -- never "all". `chosen`: name -> level. */
6157
+ const apiKeyLevelWord = (level) => (level === 'talk' ? uiSaid('set-apikeys-talk', 'Talk') : uiSaid('set-apikeys-read', 'Read'));
6158
+ function apiKeyConvPicker(chosen, onChange) {
6159
+ const box = el('div', 'apikey-convs');
6160
+ const list = conversations.filter((c) => c && c.name);
6161
+ if (!list.length) box.append(el('small', 'hint', uiSaid('set-apikeys-no-convs', 'No conversation yet')));
6162
+ const options = [{ value: '', label: uiSaid('set-apikeys-off', 'Off') }, { value: 'read', label: apiKeyLevelWord('read') }, { value: 'talk', label: apiKeyLevelWord('talk') }];
6163
+ for (const c of list) {
6164
+ const row = el('div', 'apikey-conv'); row.dataset.name = c.name;
6165
+ row.append(el('span', '', shownName(c)), KIT.Segmented({ options, value: chosen.get(c.name) ?? '', label: shownName(c), onChange: (v) => onChange(c.name, v || null) }));
6166
+ box.append(row);
6167
+ }
6168
+ return box;
6169
+ }
6170
+ const apiKeyNewConvs = new Map();
6171
+ /* The key whose conversations or journal are open under it, kept across a repaint. */
6172
+ let apiKeyOpen = null;
6173
+ async function paintApiKeyJournal(box, id) {
6174
+ const got = await fetch(`${API}/apikeys/${id}/journal`).then((r) => (r.ok ? r.json() : null)).catch(() => null);
6175
+ box.replaceChildren();
6176
+ const uses = Array.isArray(got?.uses) ? got.uses.slice(0, 50) : [];
6177
+ if (!uses.length) { box.append(el('small', 'hint', uiSaid('set-apikeys-no-use', 'No call yet'))); return; }
6178
+ for (const u of uses) {
6179
+ const line = el('div', 'apikey-use');
6180
+ const when = el('small', '', agoSaid(u.at)); when.title = new Date(u.at).toLocaleString();
6181
+ const code = el('b', '', String(u.status)); if (u.status >= 400) code.dataset.bad = 'true';
6182
+ line.append(when, el('code', '', `${u.method} ${u.route}`), code);
6183
+ box.append(line);
6184
+ }
6185
+ }
6149
6186
  async function paintApiKeys() {
6150
6187
  const got = DEVICE ? null : await fetch(`${API}/apikeys`).then((r) => (r.ok ? r.json() : null)).catch(() => null);
6151
6188
  $('settings-ch-apikeys').hidden = !got || !Array.isArray(got.keys);
@@ -6169,8 +6206,9 @@
6169
6206
  const head = el('b', '', k.label);
6170
6207
  what.append(head);
6171
6208
  const tags = el('span', 'apikey-scopes');
6172
- if (k.scopes.length) for (const sc of k.scopes) tags.append(el('span', 'chip', scopeWord(sc)));
6173
- else tags.append(el('span', 'chip', uiSaid('set-apikeys-no-scope', 'No scope')));
6209
+ const given = [...k.scopes.map((sc) => ({ text: scopeWord(sc) })),
6210
+ ...(k.conversations ?? []).map((c) => ({ text: `${shownName(conversations.find((x) => x.name === c.name) ?? { name: c.name })} · ${apiKeyLevelWord(c.level)}`, tone: c.level === 'talk' ? 'note' : undefined }))];
6211
+ tags.append(KIT.Chips(given.length ? given : [{ text: uiSaid('set-apikeys-no-scope', 'No scope') }]));
6174
6212
  what.append(tags);
6175
6213
  const by = k.createdBy ? (k.createdBy === got.me ? uiSaid('set-apikeys-by-you', 'by you') : k.createdBy) : '';
6176
6214
  const facts = [
@@ -6188,14 +6226,40 @@
6188
6226
  await paintApiKeys();
6189
6227
  } });
6190
6228
  });
6191
- acts.append(revoke);
6192
- row.append(what, acts);
6229
+ /* Its conversations, or its journal, opened under it (one at a time). */
6230
+ const more = el('div', 'apikey-more'); more.hidden = true;
6231
+ const open = async (kind) => {
6232
+ apiKeyOpen = apiKeyOpen?.id === k.id && apiKeyOpen.what === kind ? null : { id: k.id, what: kind };
6233
+ for (const b of acts.querySelectorAll('button[data-act="convs"], button[data-act="journal"]')) b.setAttribute('aria-expanded', String(apiKeyOpen?.id === k.id && apiKeyOpen.what === b.dataset.act));
6234
+ more.hidden = apiKeyOpen?.id !== k.id;
6235
+ more.replaceChildren();
6236
+ if (!apiKeyOpen || apiKeyOpen.id !== k.id) return;
6237
+ if (kind === 'journal') { more.dataset.what = 'journal'; await paintApiKeyJournal(more, k.id); return; }
6238
+ more.dataset.what = 'convs';
6239
+ more.append(apiKeyConvPicker(new Map((k.conversations ?? []).map((c) => [c.name, c.level])), async (name, level) => {
6240
+ $('apikeys-error').hidden = true;
6241
+ try { await post(`${API}/apikeys/${k.id}/conversations`, { conversation: name, level }); } catch (error) { $('apikeys-error').textContent = error.message; $('apikeys-error').hidden = false; }
6242
+ await paintApiKeys();
6243
+ }));
6244
+ };
6245
+ const convs = el('button', '', uiSaid('set-apikeys-convs', 'Conversations')); convs.type = 'button'; convs.dataset.act = 'convs';
6246
+ const journal = el('button', '', uiSaid('set-apikeys-journal', 'Journal')); journal.type = 'button'; journal.dataset.act = 'journal';
6247
+ convs.addEventListener('click', () => void open('convs'));
6248
+ journal.addEventListener('click', () => void open('journal'));
6249
+ acts.append(convs, journal, revoke);
6250
+ row.append(what, acts, more);
6193
6251
  rows.append(row);
6252
+ if (apiKeyOpen?.id === k.id) { const kind = apiKeyOpen.what; apiKeyOpen = null; void open(kind); }
6194
6253
  }
6195
6254
  }
6196
6255
  const apiKeyFormShown = (on) => {
6197
6256
  $('apikeys-form').hidden = !on; $('apikeys-new-row').hidden = on; $('apikeys-error').hidden = true;
6198
- if (on) { $('apikeys-label').value = ''; $('apikeys-days').value = '90'; for (const b of $('apikeys-scopes').querySelectorAll('input')) b.checked = false; $('apikeys-label').focus(); }
6257
+ if (on) {
6258
+ $('apikeys-label').value = ''; $('apikeys-days').value = '90'; for (const b of $('apikeys-scopes').querySelectorAll('input')) b.checked = false;
6259
+ apiKeyNewConvs.clear();
6260
+ $('apikeys-convs').replaceChildren(apiKeyConvPicker(apiKeyNewConvs, (name, level) => { if (level) apiKeyNewConvs.set(name, level); else apiKeyNewConvs.delete(name); }));
6261
+ $('apikeys-label').focus();
6262
+ }
6199
6263
  };
6200
6264
  $('apikeys-new').addEventListener('click', () => apiKeyFormShown(true));
6201
6265
  $('apikeys-cancel').addEventListener('click', () => apiKeyFormShown(false));
@@ -6204,13 +6268,15 @@
6204
6268
  $('apikeys-error').hidden = true;
6205
6269
  const days = $('apikeys-days').value;
6206
6270
  try {
6207
- const r = await post(`${API}/apikeys`, { label: $('apikeys-label').value.trim(), scopes: [...$('apikeys-scopes').querySelectorAll('input:checked')].map((b) => b.value), days: days === 'never' ? null : Number(days) });
6271
+ const scopes = [...$('apikeys-scopes').querySelectorAll('input:checked')].map((b) => b.value);
6272
+ const r = await post(`${API}/apikeys`, { label: $('apikeys-label').value.trim(), scopes, conversations: Object.fromEntries(apiKeyNewConvs), days: days === 'never' ? null : Number(days) });
6208
6273
  apiKeyFormShown(false);
6209
6274
  $('apikeys-secret').value = r.secret; $('apikeys-once').hidden = false;
6210
6275
  /* 06-11 (the owner): the configuration an AI tool takes, ready to paste -- its MCP door and the key, shown this once too. */
6211
6276
  const slug = (appName || 'clavarium').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'clavarium';
6212
6277
  $('apikeys-config').textContent = JSON.stringify({ mcpServers: { [slug]: { type: 'http', url: `${location.origin}/api/ext/mcp`, headers: { Authorization: `Bearer ${r.secret}` } } } }, null, 2);
6213
- $('apikeys-curl').textContent = `curl -H "Authorization: Bearer ${r.secret}" ${location.origin}/api/ext/v1/status`;
6278
+ /* The curl line reads what it was given: the status, or else its conversations. */
6279
+ $('apikeys-curl').textContent = `curl -H "Authorization: Bearer ${r.secret}" ${location.origin}/api/ext/v1/${scopes.includes('status') || !apiKeyNewConvs.size ? 'status' : 'conversations'}`;
6214
6280
  } catch (error) { $('apikeys-error').textContent = error.message; $('apikeys-error').hidden = false; return; }
6215
6281
  await paintApiKeys();
6216
6282
  });
package/web/index.html CHANGED
@@ -1038,6 +1038,7 @@
1038
1038
  <form id="apikeys-form" class="set-rows" autocomplete="off" hidden>
1039
1039
  <div class="set-row"><div class="set-what"><label for="apikeys-label" data-said="set-apikeys-name">Name</label><small data-said="set-apikeys-name-hint">What it is for</small></div><div class="set-control"><input id="apikeys-label" maxlength="40" spellcheck="false" required></div></div>
1040
1040
  <div class="set-row"><div class="set-what"><span data-said="set-apikeys-scopes">Scopes</span><small data-said="set-apikeys-scopes-hint">None until ticked</small></div><div class="set-control" id="apikeys-scopes"></div></div>
1041
+ <div class="set-row"><div class="set-what"><span data-said="set-apikeys-convs">Conversations</span><small data-said="set-apikeys-convs-hint">One by one: read or talk</small></div><div class="set-control" id="apikeys-convs"></div></div>
1041
1042
  <div class="set-row"><div class="set-what"><label for="apikeys-days" data-said="set-apikeys-expires">Expires</label></div><div class="set-control"><select id="apikeys-days"><option value="30" data-said="set-apikeys-30">In 30 days</option><option value="90" data-said="set-apikeys-90" selected>In 90 days</option><option value="365" data-said="set-apikeys-365">In a year</option><option value="never" data-said="set-apikeys-never">Never</option></select></div></div>
1042
1043
  <div class="action-row"><span class="error" id="apikeys-error" role="alert" hidden></span><button type="button" id="apikeys-cancel" data-said="set-apikeys-cancel">Cancel</button><button type="submit" class="primary" data-said="set-apikeys-create">Create</button></div>
1043
1044
  </form>
package/web/style.css CHANGED
@@ -1874,6 +1874,18 @@ button.tip-btn:hover, button.tip-btn[aria-expanded="true"] { color: var(--brass-
1874
1874
  /* Revoke confirmed in place: the question and its buttons under the key, never squeezing its name. */
1875
1875
  .list-item.apikey:has(.kit-confirm) { grid-template-columns: minmax(0, 1fr); }
1876
1876
  @media (max-width: 520px) { .apikeys-once input { flex-basis: 100%; } }
1877
+ /* Its conversations, one by one: a name and Off / Read / Talk; its journal, its last calls. Under the key, full width. */
1878
+ .list-item.apikey > .set-control { display: flex; flex-wrap: wrap; gap: 6px; justify-content: flex-end; }
1879
+ .apikey-more { grid-column: 1 / -1; display: flex; flex-direction: column; gap: 6px; padding-top: 6px; }
1880
+ .apikey-convs { display: flex; flex-direction: column; gap: 6px; width: 100%; }
1881
+ .apikey-conv { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; }
1882
+ .apikey-conv > span { min-width: 0; overflow-wrap: anywhere; font-size: .875rem; }
1883
+ .apikey-use { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: 8px; align-items: baseline; font-size: .75rem; }
1884
+ .apikey-use > code { overflow-wrap: anywhere; }
1885
+ .apikey-use > small { color: var(--ink2); white-space: nowrap; }
1886
+ .apikey-use > b[data-bad] { color: var(--danger); }
1887
+ /* A phone: its buttons under its name, never squeezing it. */
1888
+ @media (max-width: 640px) { .list-item.apikey { grid-template-columns: minmax(0, 1fr); } .list-item.apikey > .set-control { justify-self: start; justify-content: flex-start; } }
1877
1889
  #apikeys-where { flex: 1 1 auto; min-width: 0; overflow-wrap: anywhere; font-family: ui-monospace, Menlo, Consolas, monospace; font-size: .75rem; }
1878
1890
  .mono-cut { font-family: ui-monospace, Menlo, Consolas, monospace; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1879
1891
  #settings #export-note { max-width: none; text-align: left; margin: 0; order: 0; flex: none; }